package top.likeqc.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.likeqc.common.dto.SysMenuDto;
import top.likeqc.common.lang.Result;
import top.likeqc.entity.SysMenu;
import top.likeqc.entity.SysRoleMenu;
import top.likeqc.entity.SysUser;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 前端控制器
 *
 * @author likeqc
 * @since 2022-03-14
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {
    
    /**
     * 获取当前用户的菜单、权限信息
     *
     * @param principal
     * @return
     */
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        // 获取权限信息
        String authority =
                sysUserService.getUserAuthorityInfo(
                        sysUser.getId()); // ROLE_admin,sys:user:list,...
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authority, ",");

        // 获取导航栏信息
        List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();
        return Result.success(
                MapUtil.builder().put("authority", authorityInfoArray).put("nav", navs).map());
    }
    
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id) {
        return Result.success(sysMenuService.getById(id));
    }
    
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    @GetMapping("/list")
    public Result list() {
        List<SysMenu> sysMenus = sysMenuService.tree();
        return Result.success(sysMenus);
    }
    
    @PreAuthorize("hasAnyAuthority('sys:menu:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setCreated(LocalDateTime.now());
        sysMenuService.save(sysMenu);
        return Result.success(sysMenu);
    }
    
    @PreAuthorize("hasAnyAuthority('sys:menu:update')")
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);
        // 修改了菜单信息，及时更新相关权限 redis 缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.success(sysMenu);
    }
    
    @PreAuthorize("hasAnyAuthority('sys:menu:delete')")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return Result.fail("请先删除子菜单");
        }
        // 清除相关缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);
        // 删除
        sysMenuService.removeById(id);
        // 同步删除中间表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
        return Result.success("");
    }
}
